package com.asm.blog.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.asm.blog.common.lang.Result;
import com.asm.blog.entity.Blog;
import com.asm.blog.entity.User;
import com.asm.blog.service.BlogService;
import com.asm.blog.service.UserService;
import com.asm.blog.util.ShiroUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author asm付
 * @since 2021-06-01
 */
@RestController       // 相当于 @Controller + @ResponseBody
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    BlogService blogService;

    /**
     * 列表
     * @param  currentPage   当前页
     *
     */
    @PostMapping("/list")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage)
    {
        Page page = new Page(currentPage, 2);

        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("id"));

        return Result.succ(pageData);

    }


    /**
     * 详情
     * @param  id
     *
     */
    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable("id") Long id)
    {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客不存在或被删除！");

        return Result.succ(blog);
    }



    /**
     * 编辑
     * @param   title
     * @param   description
     * @param   content
     *
     */
    @RequiresAuthentication
    @PostMapping("/edit")
    public Result edit(@Validated @RequestBody Blog blog)
    {
        Blog saveObj = null;

        Long shiroUid = ShiroUtil.getProfile().getId();

        // 1. 有ID是更新
        if(blog.getId() != null)
        {
            // 1.1 获取文章对象
            saveObj = blogService.getById(blog.getId());

            // 1.2 判断是否存在
            Assert.notNull(saveObj, "文章不存在或已删除");

            // 1.2 只能编辑自己文章

            Assert.isTrue(saveObj.getUserId().equals(shiroUid), "只能编辑自己的文章哦");

        // 2. 没有 ID 则是创建
        }else{

            // 2.1 实例一个对象准备保存
            saveObj = new Blog();
            saveObj.setUserId(shiroUid);
            saveObj.setCreated(LocalDateTime.now());
            saveObj.setStatus(0);

        }

        // 3 复制对象  , 第三参数开始为忽略的字段
        BeanUtil.copyProperties(blog, saveObj, "id","userId","created","status");

        // 4. 保存或更新
        blogService.saveOrUpdate(saveObj);

        return Result.succ(null);
    }




}
